package in.equilibr.ingredients.controller;

import in.equilibr.ingredients.dao.IngredientDao;
import in.equilibr.ingredients.model.Ingredient;
import in.equilibr.ingredients.service.IngredientService;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping
public class IngredientController {
	private static final Logger logger = LoggerFactory
			.getLogger(IngredientController.class);

	@Autowired
	private IngredientDao ingredientDao;

	@Autowired
	private IngredientService ingredientService;

	public void init() {

	}

	// get 50 ingredients with most calories
	@RequestMapping(method = RequestMethod.GET, value = "/")
	public ModelAndView showIngredients() {

		List<Ingredient> ingredients = ingredientDao.getIngredients(50);
		logger.info("There are " + ingredients.size() + " ingredients with most calories found.");
		if (ingredients.size() > 0) {
			logger.info("The most high-caloric ingredient is " + ingredients.get(0).getName());
		}
		return ingredientService.buildListView(ingredients);
	}

	// Neue Stadt anlegen
	@RequestMapping(method = RequestMethod.POST, value = "/ingredient/add")
	public String addIngredient(@ModelAttribute("ingredient") Ingredient ingredient,
			BindingResult result) {
		logger.info("Add new ingredient " + ingredient.getName() + ".");

		ingredientDao.addIngredient(ingredient);

		return "redirect:/";
	}

	// Delete per URL and via AJAX
	@RequestMapping(method = RequestMethod.GET, value = "/ingredient/delete/{id}")
	public String deleteIngredinet(@PathVariable("id") int id) {
		logger.info("Delete record " + id + ".");

		ingredientDao.deleteIngredientById(id);

		return "redirect:/";
	}

	// Create new Index
	@RequestMapping(method = RequestMethod.GET, value = "/createsearchindex")
	public String createSearchIndex() throws InterruptedException {
		logger.info("Create Lucene-Index.");

		ingredientDao.createSearchIndex();

		return "redirect:/";
	}

	// Search function GET
	@RequestMapping(method = RequestMethod.GET, value = "/ingredient/search")
	public ModelAndView getSearchResult(@RequestParam("term") String term) {
		List<Ingredient> ingredients = ingredientDao.searchIngredient(term);
		logger.info("There are " + ingredients.size() + " ingredients found.");

		return ingredientService.buildListView(ingredients);
	}

	// Search function for Autocomplete POST
	@RequestMapping(method = RequestMethod.POST, value = "/ingredient/search")
	public ResponseEntity<String> getAutocompleteResult(
			@RequestParam("term") String term) throws IOException {

		// New Response-Header is necessary, otherwise ISO-coded response
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");

		List<String> ingredients = ingredientDao.searchIngredientName(term);

		if (ingredients.size() == 0) {
			logger.info("No records in Database - try auto correction.");
			ingredients = ingredientDao.searchSimilarIngredients(term);
		} else {
			logger.info("There are " + ingredients.size()
					+ " ingredients found - Autocomplete.");
		}
		String json = ingredientService.convertJson(ingredients);
		return new ResponseEntity<String>(json, responseHeaders,
				HttpStatus.CREATED);
	}
}
